"""法考题库数据"""
from typing import List, Dict, Any, Optional

# 法考科目及权重配置
SUBJECT_WEIGHTS = {
    "民法": 0.18,      # 18%
    "民诉": 0.12,      # 12%
    "刑法": 0.15,      # 15%
    "刑诉": 0.10,      # 10%
    "行政": 0.12,      # 12%
    "商经": 0.15,      # 15%
    "三国": 0.08,      # 8%
    "综合": 0.10,      # 10% (跨科目综合题)
}

# 科目中文名称映射
SUBJECT_NAMES = {
    "civil_law": "民法",
    "civil_procedure": "民诉",
    "criminal_law": "刑法",
    "criminal_procedure": "刑诉",
    "administrative": "行政",
    "commercial": "商经",
    "international": "三国",
    "comprehensive": "综合",
}

# 题库数据
QUESTION_BANK: List[Dict[str, Any]] = [
    # ========== 民法 ==========
    {
        "question_id": "civil_001",
        "content": "甲公司与乙公司签订买卖合同，约定甲向乙交付货物后10日内付款。甲按期交付货物，但乙逾期未付款。关于甲的权利，下列说法正确的是：",
        "options": [
            "选项A：甲只能要求乙支付货款",
            "选项B：甲可以解除合同并要求乙承担违约责任",
            "选项C：甲可以要求乙支付货款及逾期利息",
            "选项D：甲只能等待乙主动付款"
        ],
        "correct_answer": "选项C",
        "explanation": "根据《民法典》规定，债务人逾期履行债务的，债权人可以要求其支付逾期利息。同时，甲作为债权人，有权要求乙支付货款及承担违约责任。",
        "type": "single_choice",
        "difficulty": "medium",
        "category": "民法",
        "subject": "civil_law",
        "knowledge_points": ["合同法", "违约责任", "逾期履行"],
        "year": None,  # 真题年份，None表示非真题
        "exam_type": None,  # 考试类型：客观题/主观题
        "source": "manual",  # 题目来源：manual/scraped/mock
        "difficulty_score": 60.0,  # 难度评分 0-100
        "wrong_count": 0,  # 做错次数
        "correct_count": 0  # 做对次数
    },
    {
        "question_id": "civil_002",
        "content": "关于民事法律行为的效力，下列说法错误的是：",
        "options": [
            "选项A：无民事行为能力人实施的民事法律行为无效",
            "选项B：违反法律、行政法规的强制性规定的民事法律行为无效",
            "选项C：违背公序良俗的民事法律行为无效",
            "选项D：限制民事行为能力人实施的民事法律行为一律无效"
        ],
        "correct_answer": "选项D",
        "explanation": "限制民事行为能力人实施的纯获利益的民事法律行为或者与其年龄、智力、精神健康状况相适应的民事法律行为有效；其他民事法律行为经法定代理人同意或追认后有效。",
        "type": "single_choice",
        "difficulty": "medium",
        "category": "民法",
        "subject": "civil_law",
        "knowledge_points": ["民事法律行为", "行为能力"],
        "year": None,
        "exam_type": None,
        "source": "manual",
        "difficulty_score": 65.0,
        "wrong_count": 0,
        "correct_count": 0
    },
    
    # ========== 民诉 ==========
    {
        "question_id": "civ_proc_001",
        "content": "关于民事诉讼的管辖，下列说法正确的是：",
        "options": [
            "选项A：合同纠纷案件只能由合同履行地人民法院管辖",
            "选项B：合同纠纷案件只能由被告住所地人民法院管辖",
            "选项C：合同纠纷案件可以由合同履行地或被告住所地人民法院管辖",
            "选项D：合同纠纷案件只能由合同签订地人民法院管辖"
        ],
        "correct_answer": "选项C",
        "explanation": "根据《民事诉讼法》规定，合同纠纷案件可以由合同履行地或被告住所地人民法院管辖。",
        "type": "single_choice",
        "difficulty": "easy",
        "category": "民诉",
        "subject": "civil_procedure",
        "knowledge_points": ["民事诉讼", "管辖"],
        "year": None,
        "exam_type": None,
        "source": "manual",
        "difficulty_score": 40.0,
        "wrong_count": 0,
        "correct_count": 0
    },
    {
        "question_id": "civ_proc_002",
        "content": "关于民事诉讼中的举证责任，下列说法正确的是：",
        "options": [
            "选项A：所有案件都适用'谁主张，谁举证'原则",
            "选项B：特殊侵权案件实行举证责任倒置",
            "选项C：原告对被告的过错不承担举证责任",
            "选项D：法院应当主动收集所有证据"
        ],
        "correct_answer": "选项B",
        "explanation": "特殊侵权案件（如环境污染、医疗损害等）实行举证责任倒置，由被告证明自己无过错或不存在因果关系。",
        "type": "single_choice",
        "difficulty": "medium",
        "category": "民诉",
        "subject": "civil_procedure",
        "knowledge_points": ["举证责任", "特殊侵权"],
        "year": None,
        "exam_type": None,
        "source": "manual",
        "difficulty_score": 70.0,
        "wrong_count": 0,
        "correct_count": 0
    },
    
    # ========== 刑法 ==========
    {
        "question_id": "criminal_001",
        "content": "关于犯罪构成要件，下列说法正确的是：",
        "options": [
            "选项A：犯罪构成包括主观要件和客观要件",
            "选项B：犯罪构成只包括客观要件",
            "选项C：犯罪构成只包括主观要件",
            "选项D：犯罪构成不包括主体要件"
        ],
        "correct_answer": "选项A",
        "explanation": "犯罪构成包括四个方面：犯罪主体、犯罪主观方面、犯罪客体、犯罪客观方面。",
        "type": "single_choice",
        "difficulty": "easy",
        "category": "刑法",
        "subject": "criminal_law",
        "knowledge_points": ["犯罪构成", "刑法总则"],
        "year": None,
        "exam_type": None,
        "source": "manual",
        "difficulty_score": 35.0,
        "wrong_count": 0,
        "correct_count": 0
    },
    {
        "question_id": "criminal_002",
        "content": "关于正当防卫，下列说法错误的是：",
        "options": [
            "选项A：正当防卫必须针对正在进行的不法侵害",
            "选项B：正当防卫不能明显超过必要限度",
            "选项C：对正在进行行凶、杀人等严重危及人身安全的暴力犯罪，可以无限防卫",
            "选项D：正当防卫只能针对不法侵害人本人"
        ],
        "correct_answer": "选项C",
        "explanation": "对正在进行行凶、杀人、抢劫、强奸、绑架等严重危及人身安全的暴力犯罪，采取防卫行为，造成不法侵害人伤亡的，不属于防卫过当，不负刑事责任。但这不是'无限防卫'，仍需符合正当防卫的其他要件。",
        "type": "single_choice",
        "difficulty": "hard",
        "category": "刑法",
        "subject": "criminal_law",
        "knowledge_points": ["正当防卫", "违法阻却事由"],
        "year": None,
        "exam_type": None,
        "source": "manual",
        "difficulty_score": 85.0,
        "wrong_count": 0,
        "correct_count": 0
    },
    
    # ========== 刑诉 ==========
    {
        "question_id": "crim_proc_001",
        "content": "关于刑事诉讼的管辖，下列说法正确的是：",
        "options": [
            "选项A：刑事案件只能由犯罪地人民法院管辖",
            "选项B：刑事案件只能由被告人居住地人民法院管辖",
            "选项C：刑事案件可以由犯罪地或被告人居住地人民法院管辖",
            "选项D：刑事案件只能由最初受理的人民法院管辖"
        ],
        "correct_answer": "选项C",
        "explanation": "根据《刑事诉讼法》规定，刑事案件由犯罪地的人民法院管辖。如果由被告人居住地的人民法院审判更为适宜的，可以由被告人居住地的人民法院管辖。",
        "type": "single_choice",
        "difficulty": "medium",
        "category": "刑诉",
        "subject": "criminal_procedure",
        "knowledge_points": ["刑事诉讼", "管辖"],
        "year": None,
        "exam_type": None,
        "source": "manual",
        "difficulty_score": 55.0,
        "wrong_count": 0,
        "correct_count": 0
    },
    {
        "question_id": "crim_proc_002",
        "content": "关于刑事诉讼中的强制措施，下列说法正确的是：",
        "options": [
            "选项A：逮捕是最轻的强制措施",
            "选项B：取保候审和监视居住可以同时适用",
            "选项C：拘留的期限最长不得超过37天",
            "选项D：只有公安机关可以决定逮捕"
        ],
        "correct_answer": "选项C",
        "explanation": "拘留的期限：一般案件3日，特殊情况下可以延长至7日，对于流窜作案、多次作案、结伙作案的重大嫌疑分子，可以延长至30日，加上检察院审查批捕的7日，最长37日。",
        "type": "single_choice",
        "difficulty": "medium",
        "category": "刑诉",
        "subject": "criminal_procedure",
        "knowledge_points": ["强制措施", "拘留"],
        "year": None,
        "exam_type": None,
        "source": "manual",
        "difficulty_score": 70.0,
        "wrong_count": 0,
        "correct_count": 0
    },
    
    # ========== 行政法 ==========
    {
        "question_id": "admin_001",
        "content": "关于行政诉讼的受案范围，下列说法正确的是：",
        "options": [
            "选项A：所有行政行为都可以提起行政诉讼",
            "选项B：只有具体行政行为可以提起行政诉讼",
            "选项C：抽象行政行为也可以提起行政诉讼",
            "选项D：内部行政行为也可以提起行政诉讼"
        ],
        "correct_answer": "选项B",
        "explanation": "行政诉讼的受案范围主要是具体行政行为。抽象行政行为（如行政法规、规章）一般不能直接提起行政诉讼，但可以在对具体行政行为提起诉讼时一并请求审查。",
        "type": "single_choice",
        "difficulty": "medium",
        "category": "行政",
        "subject": "administrative",
        "knowledge_points": ["行政诉讼", "受案范围"],
        "year": None,
        "exam_type": None,
        "source": "manual",
        "difficulty_score": 65.0,
        "wrong_count": 0,
        "correct_count": 0
    },
    {
        "question_id": "admin_002",
        "content": "关于行政处罚的决定程序，下列说法正确的是：",
        "options": [
            "选项A：所有行政处罚都可以适用简易程序",
            "选项B：对公民处以200元以下的罚款可以适用简易程序",
            "选项C：对法人处以1000元以下的罚款可以适用简易程序",
            "选项D：警告不能适用简易程序"
        ],
        "correct_answer": "选项B",
        "explanation": "违法事实确凿并有法定依据，对公民处以200元以下、对法人或者其他组织处以3000元以下罚款或者警告的行政处罚的，可以适用简易程序。",
        "type": "single_choice",
        "difficulty": "medium",
        "category": "行政",
        "subject": "administrative",
        "knowledge_points": ["行政处罚", "简易程序"],
        "year": None,
        "exam_type": None,
        "source": "manual",
        "difficulty_score": 60.0,
        "wrong_count": 0,
        "correct_count": 0
    },
    
    # ========== 商经 ==========
    {
        "question_id": "commercial_001",
        "content": "关于公司股东的权利，下列说法正确的是：",
        "options": [
            "选项A：股东只有收益权，没有参与公司管理的权利",
            "选项B：股东有权查阅公司章程、股东会会议记录等",
            "选项C：股东无权提起股东代表诉讼",
            "选项D：股东不能转让其持有的股份"
        ],
        "correct_answer": "选项B",
        "explanation": "股东享有知情权，有权查阅公司章程、股东名册、公司债券存根、股东大会会议记录、董事会会议决议、监事会会议决议、财务会计报告等。",
        "type": "single_choice",
        "difficulty": "medium",
        "category": "商经",
        "subject": "commercial",
        "knowledge_points": ["公司法", "股东权利"],
        "year": None,
        "exam_type": None,
        "source": "manual",
        "difficulty_score": 65.0,
        "wrong_count": 0,
        "correct_count": 0
    },
    {
        "question_id": "commercial_002",
        "content": "关于有限责任公司的设立，下列说法错误的是：",
        "options": [
            "选项A：有限责任公司由50个以下股东出资设立",
            "选项B：有限责任公司的注册资本为在公司登记机关登记的全体股东认缴的出资额",
            "选项C：有限责任公司可以设立一人有限责任公司",
            "选项D：有限责任公司的股东只能是自然人"
        ],
        "correct_answer": "选项D",
        "explanation": "有限责任公司的股东可以是自然人、法人或其他组织。一人有限责任公司的股东可以是自然人，也可以是法人。",
        "type": "single_choice",
        "difficulty": "medium",
        "category": "商经",
        "subject": "commercial",
        "knowledge_points": ["公司法", "公司设立"],
        "year": None,
        "exam_type": None,
        "source": "manual",
        "difficulty_score": 70.0,
        "wrong_count": 0,
        "correct_count": 0
    },
    
    # ========== 三国法 ==========
    {
        "question_id": "international_001",
        "content": "关于国际法的渊源，下列说法正确的是：",
        "options": [
            "选项A：国际条约不是国际法的渊源",
            "选项B：国际习惯是国际法的渊源之一",
            "选项C：一般法律原则不能作为国际法的渊源",
            "选项D：国际法院的判决对其他国家有约束力"
        ],
        "correct_answer": "选项B",
        "explanation": "国际法的渊源包括：国际条约、国际习惯、一般法律原则。国际法院的判决只对当事国及本案有约束力，不是国际法的渊源。",
        "type": "single_choice",
        "difficulty": "hard",
        "category": "三国",
        "subject": "international",
        "knowledge_points": ["国际法", "法律渊源"],
        "year": None,
        "exam_type": None,
        "source": "manual",
        "difficulty_score": 80.0,
        "wrong_count": 0,
        "correct_count": 0
    },
    {
        "question_id": "international_002",
        "content": "关于冲突规范，下列说法正确的是：",
        "options": [
            "选项A：冲突规范直接规定当事人的权利义务",
            "选项B：冲突规范只存在于国际私法中",
            "选项C：冲突规范是间接规范，只指定适用何国法律",
            "选项D：冲突规范不能适用于国内法律冲突"
        ],
        "correct_answer": "选项C",
        "explanation": "冲突规范是间接规范，它不直接规定当事人的权利义务，而是指定适用何国法律来确定当事人的权利义务关系。",
        "type": "single_choice",
        "difficulty": "hard",
        "category": "三国",
        "subject": "international",
        "knowledge_points": ["国际私法", "冲突规范"],
        "year": None,
        "exam_type": None,
        "source": "manual",
        "difficulty_score": 85.0,
        "wrong_count": 0,
        "correct_count": 0
    },
    
    # ========== 综合题 ==========
    {
        "question_id": "comp_001",
        "content": "甲公司与乙公司签订买卖合同，约定由丙公司向乙公司交付货物。后丙公司未按约定交付货物，乙公司要求甲公司承担违约责任。同时，乙公司发现甲公司在签订合同时存在欺诈行为。关于本案的法律适用，下列说法正确的是：",
        "options": [
            "选项A：本案只涉及合同法问题",
            "选项B：本案涉及合同法和侵权法的竞合",
            "选项C：本案涉及合同履行、违约责任和合同效力问题",
            "选项D：本案只涉及侵权法问题"
        ],
        "correct_answer": "选项C",
        "explanation": "本案涉及多个法律问题：1）第三人履行合同（丙公司代为履行）；2）违约责任（丙公司未履行，甲公司承担责任）；3）合同效力（欺诈可撤销）。属于跨科目的综合题。",
        "type": "single_choice",
        "difficulty": "hard",
        "category": "综合",
        "subject": "comprehensive",
        "knowledge_points": ["合同法", "民法", "合同效力", "违约责任"],
        "related_subjects": ["civil_law", "commercial"],
        "year": None,
        "exam_type": None,
        "source": "manual",
        "difficulty_score": 90.0,
        "wrong_count": 0,
        "correct_count": 0
    },
    {
        "question_id": "comp_002",
        "content": "甲因涉嫌盗窃罪被公安机关立案侦查。在侦查过程中，甲主动交代了公安机关尚未掌握的另一起抢劫罪。后甲因盗窃罪被判处有期徒刑3年，因抢劫罪被判处有期徒刑5年。关于本案的程序和实体问题，下列说法正确的是：",
        "options": [
            "选项A：甲主动交代的抢劫罪属于自首，可以从轻或减轻处罚",
            "选项B：对甲应当数罪并罚，执行有期徒刑8年",
            "选项C：本案只涉及刑事诉讼程序问题",
            "选项D：甲的行为不构成自首"
        ],
        "correct_answer": "选项A",
        "explanation": "本案涉及刑法和刑诉的综合问题：1）自首的认定（主动交代司法机关未掌握的其他罪行）；2）数罪并罚（总和刑期8年，但需适用限制加重原则）；3）程序上涉及侦查、起诉、审判。",
        "type": "single_choice",
        "difficulty": "hard",
        "category": "综合",
        "subject": "comprehensive",
        "knowledge_points": ["自首", "数罪并罚", "刑事诉讼"],
        "related_subjects": ["criminal_law", "criminal_procedure"],
        "year": None,
        "exam_type": None,
        "source": "manual",
        "difficulty_score": 95.0,
        "wrong_count": 0,
        "correct_count": 0
    },
]


def get_questions_by_subject(subject: str) -> List[Dict[str, Any]]:
    """根据科目获取题目（优先从Redis读取，内存作为后备）"""
    # 优先从Redis读取
    try:
        from app.services.question_storage_service import question_storage_service
        questions = question_storage_service.get_questions_by_subject(subject)
        if questions:
            return questions
    except Exception as e:
        print(f"从Redis读取科目题目失败，使用内存存储: {e}")
    
    # 从内存读取（后备）
    return [q for q in QUESTION_BANK if q.get("subject") == subject]


def get_questions_by_category(category: str) -> List[Dict[str, Any]]:
    """根据分类获取题目（优先从Redis读取，内存作为后备）"""
    # 优先从Redis读取
    try:
        from app.services.question_storage_service import question_storage_service
        # 通过category索引获取
        if question_storage_service.redis:
            question_ids = question_storage_service.redis.smembers(f"question_ids:by_category:{category}")
            questions = []
            for qid in question_ids:
                if isinstance(qid, bytes):
                    qid = qid.decode('utf-8')
                question = question_storage_service.get_question_by_id(qid)
                if question:
                    questions.append(question)
            if questions:
                return questions
    except Exception as e:
        print(f"从Redis读取分类题目失败，使用内存存储: {e}")
    
    # 从内存读取（后备）
    return [q for q in QUESTION_BANK if q.get("category") == category]


def get_all_questions() -> List[Dict[str, Any]]:
    """获取所有题目（优先从Redis读取，内存作为后备）"""
    # 优先从Redis读取
    try:
        from app.services.question_storage_service import question_storage_service
        questions = question_storage_service.get_all_questions()
        if questions:
            return questions
    except Exception as e:
        print(f"从Redis读取所有题目失败，使用内存存储: {e}")
    
    # 从内存读取（后备）
    return QUESTION_BANK


def get_question_by_id(question_id: str) -> Dict[str, Any] | None:
    """根据ID获取题目（优先从Redis读取，内存作为后备）"""
    # 优先从Redis读取
    try:
        from app.services.question_storage_service import question_storage_service
        question = question_storage_service.get_question_by_id(question_id)
        if question:
            return question
    except Exception as e:
        print(f"从Redis读取题目失败，使用内存存储: {e}")
    
    # 从内存读取（后备）
    for q in QUESTION_BANK:
        if q.get("question_id") == question_id:
            return q
    return None


def get_question_count_by_subject() -> Dict[str, int]:
    """统计各科目题目数量"""
    counts = {}
    for subject in SUBJECT_NAMES.keys():
        counts[subject] = len(get_questions_by_subject(subject))
    return counts


def add_questions(questions: List[Dict[str, Any]]) -> Dict[str, Any]:
    """
    添加题目到题库（存储到Redis，同时更新内存）
    
    Args:
        questions: 题目列表
        
    Returns:
        添加结果统计
    """
    from app.services.question_storage_service import question_storage_service
    
    # 存储到Redis
    result = question_storage_service.add_questions(questions)
    
    # 同时更新内存中的QUESTION_BANK（作为后备）
    for question in questions:
        question_id = question.get("question_id")
        if question_id:
            # 检查是否已存在
            existing = get_question_by_id(question_id)
            if not existing:
                QUESTION_BANK.append(question)
    
    return result

